package com.ydsungan.worldbook.controller;

import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.wordnik.swagger.annotations.ApiOperation;
import com.ydsungan.worldbook.pojo.Book;
import com.ydsungan.worldbook.pojo.DownloadInfoMap;
import com.ydsungan.worldbook.pojo.User;
import com.ydsungan.worldbook.service.BookService;
import com.ydsungan.worldbook.service.UserService;
import com.ydsungan.worldbook.utils.FileUtils;
import com.ydsungan.worldbook.utils.HttpClientUtil;
import com.ydsungan.worldbook.utils.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(path = "/book")
@CrossOrigin(allowCredentials="true",maxAge = 3600)   //解决跨域

public class BookController {

    @Value("${root_user_id}")
    private String root_user_id;

    @Value("${recommendation_num}")
    private String recommendation_num;

    @Value("${acquired_score_num}")
    private String acquired_score_num;


    @Value("${book_directory}")
    private String book_directory;


    @Autowired
    private UserService userService;

    @Autowired
    private BookService bookService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @ApiOperation(value="用户上传图书",notes = "其中需要把MultipartFile转为File存储")
    @RequestMapping(value = "/addBook", method = RequestMethod.POST)
    @CrossOrigin(allowCredentials="true",maxAge = 3600)   //解决跨域
    public JSONResult upload(MultipartFile file, String bookName, String userId, String score){

        try {
            if (file == null) {
                logger.error("File cannot be empty");
                return JSONResult.errorMsg("文件不能为空");
            }
            FileUtils.multipartfileTofile(file);
            Book book = HttpClientUtil.parseApi(bookName);
            if(book!=null){
                book.setBelong(Integer.parseInt(userId));
                book.setDownloadNum(0);
                book.setFileName(file.getOriginalFilename());
                book.setUploadTime(new Date());
                bookService.addBook(book);
            }
            //修改用户的积分
            User user = new User();
            user.setId(Integer.parseInt(userId));
            user.setScore(Integer.parseInt(score) + Integer.parseInt(acquired_score_num));
            userService.updateUser(user);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("File upload failed");
            return JSONResult.errorMsg("文件上传失败");
        }

        return JSONResult.ok();
    }

    @ApiOperation(value="主页图书展示列表",notes = "只展示网站管理员上传的图书,网站管理员的账号定义在Application.properties中的root_user_id")
    @RequestMapping(value = "/home", method = RequestMethod.GET)
    @CrossOrigin(allowCredentials="true",maxAge = 3600)   //解决跨域
    public JSONResult getHomePageBook(){
        //将最近上传的俩本书展示出来
        Map map = new HashMap();

        map.put("belong", Integer.parseInt(root_user_id));
        List<Book> list = bookService.getBookByMap(map);

        return JSONResult.ok(list.subList(list.size()-2,list.size()));
    }

    @ApiOperation(value="网页右侧的推荐图书列表")
    @RequestMapping(value = "/recommendation", method = RequestMethod.GET)
    @CrossOrigin(allowCredentials="true",maxAge = 3600)   //解决跨域
    public JSONResult getRecommendationBook(){

        List<Book> list = bookService.getBookOrderByDownloadNum(Integer.parseInt(recommendation_num));
        return JSONResult.ok(list);
    }

    @ApiOperation(value="获取用户的基本信息，包括用户的积分，上传书本数目，下载书本数目")
    @RequestMapping(value = "/userInfo", method = RequestMethod.GET)
    @CrossOrigin(allowCredentials="true",maxAge = 3600)   //解决跨域
    public JSONResult getUserInfo(String userId){


        //用户的积分，上传了多少本书，下载了多少本书，有多少书正在审核
        Map map = new HashMap();
        map.put("id",Integer.parseInt(userId));
        List<User> list = userService.getUserByMap(map);

        Map bookMap = new HashMap();
        bookMap.put("belong",Integer.parseInt(userId));
        List<Book> bookList = bookService.getBookByMap(bookMap);

        map.put("score",list.get(0).getScore());
        map.put("uploadBookNum", bookList.size());
        return JSONResult.ok(map);
    }

    @ApiOperation(value="下载图书")
    @PostMapping("/download")
    @CrossOrigin(allowCredentials="true",maxAge = 3600)   //解决跨域
    public void download(@RequestBody DownloadInfoMap map, HttpServletResponse response) throws IOException {


        logger.info(book_directory + "下载内容:" + map.getFileName() + "bookId" +  map.getBookId() + "userId: " + map.getUserId());

        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + map.getFileName());

        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(book_directory, map.getFileName())));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        logger.info(map.getFileName() + "下载成功");
    }
}
